<template>
  <a-upload
    name="file"
    :show-upload-list="false"
    list-type="picture-card"
    :before-upload="beforeUpload"
  >
    <div v-if="imageUrl" class="preview">
      <img :src="imageUrl" alt="image" />
      <div class="delete">
        <DeleteOutlined
          class="btn"
          @click="
            (e) => {
              e.stopPropagation();
              removeImg();
            }
          "
        />
      </div>
    </div>
    <div v-else :style="{ color: '#dedede' }">
      <LoadingOutlined v-if="uploading" />
      <PlusOutlined v-else />
      <div>上传</div>
    </div>
  </a-upload>
</template>

<script setup>
import { getCurrentInstance, ref } from "vue";
import { LoadingOutlined, PlusOutlined } from "@ant-design/icons-vue";
import _ from "lodash";

const { proxy } = getCurrentInstance();
const props = defineProps({ img: [Object, String] });
const uploading = ref(false);
const imageUrl = ref(props.img);

const emit = defineEmits(["update:img"]);

const beforeUpload = (file) => {
  const imgTypes = ["image/jpeg", "image/png", "image/jpg"];
  const isJPG = _.includes(imgTypes, file.type);

  if (!isJPG) {
    proxy.$message.error("仅允许上传的文件类型JPG,JPEG,PNG!");
  }
  const isLt20M = file.size / 1024 / 1024 < 20;
  if (!isLt20M) {
    proxy.$message.error("文件大小不能超过20MB!");
  }
  if (isJPG && isLt20M) {
    previewAndUpload(file);
  }
  return false;
};

const previewAndUpload = (img) => {
  uploading.value = true;
  const reader = new FileReader();
  reader.addEventListener("load", () => {
    uploading.value = false;
    imageUrl.value = reader.result;
    // fire parent callback
    emit("update:img", img);
  });
  reader.readAsDataURL(img);
};

const removeImg = () => {
  imageUrl.value = null;
  // fire parent callback
  emit("update:img", null);
};
</script>

<style lang="less" scoped>
.preview {
  width: 100%;
  height: 100%;
  position: relative;

  img {
    width: 100%;
    height: 100%;
    object-fit: contain;
  }

  .delete {
    visibility: hidden;
    position: absolute;
    left: 0;
    top: 0;
    width: 100%;
    height: 100%;
    display: flex;
    align-items: center;
    justify-content: center;
    color: #fff;
    background-color: rgba(0, 0, 0, 0.5);

    .btn:hover {
      color: red;
    }
  }

  &:hover {
    .delete {
      visibility: visible;
    }
  }
}
</style>
